package cn.sq.musicserver.plug.model.jsososo;

import cn.sq.musicserver.config.SQConstant;
import cn.sq.musicserver.exception.PlugError;
import cn.sq.musicserver.music.entity.DownloadParam;
import cn.sq.musicserver.music.entity.SqMusic;
import cn.sq.musicserver.music.service.impl.SqMusicServiceImpl;
import cn.sq.musicserver.plug.entity.PlugLyicResult;
import cn.sq.musicserver.plug.entity.PlugSearchResult;
import cn.sq.musicserver.plug.hander.MusicInfoSearc;
import cn.sq.musicserver.plug.model.jsososo.entity.*;
import cn.sq.musicserver.plug.model.jsososo.handle.JsososoService;
import cn.sq.musicserver.set.entity.SqSet;
import cn.sq.musicserver.set.service.impl.SqSetServiceImpl;
import cn.sq.musicserver.utils.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.github.classgraph.utils.Join;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: SQ
 * Date: 2020/12/17
 * Time: 15:24
 * Description:
 */
@Slf4j
@Component
public class JsososoHander extends MusicInfoSearc {
    @Autowired
    JsososoService jsososoService;
    @Autowired
    SqSetServiceImpl setService;
    @Autowired
    SqMusicServiceImpl musicService;

    @Override
    public String PlugName() {
        return "Jsososo";
    }

    @Override
    public String Plugversion() {
        return "1.0";
    }

    /**
     * 稍后版本支持文件 歌曲文件搜索
     * @param pagersize    每页多少条
     * @param pageindex    当前页
     * @param Keywords    歌曲名称
     * @param music        歌曲文件（用于音频检索）
     * @param set        插件设置
     * @param data
     * @return
     * @throws Exception
     */
    @Override
    public PlugSearchResult musicInfoSearc(Integer pagersize, Integer pageindex, String Keywords, File music, List<SqSet> set, Map<String, String> data) throws PlugError {
        SearchParam searchParam = new SearchParam().setKey(Keywords).setPageNo(pageindex + "").setPageSize(pagersize + "").setType_p(data.get("queue")).setType(data.get("type"));
        String p = data.get("queue");
        searchParam.setType_p(p);
        SearchResult search = jsososoService.search(searchParam);
        PlugSearchResult plugSearchResult = new PlugSearchResult();
        if (search.getResult() == 100) {
            plugSearchResult.setPlugMusicSearchCount(search.getData().getTotal())
                    .setPlugMusicSearchSize(search.getData().getPageSize())
                    .setPlugMusicSearchIndex(search.getData().getPageNo());
            List<SearchResult.DataBean.ListBean> list = search.getData().getList();
            List<PlugSearchResult.Song> Rressong = new ArrayList<>();
            list.forEach(iteam -> {
                PlugSearchResult.Song song = new PlugSearchResult.Song();
                song.setId(iteam.getId());
                song.setMusicName(iteam.getName())
                        .setMusicAlbum(iteam.getAl().getName());
                List<String> artists = new ArrayList<String>();
                iteam.getAr().forEach(ar -> {
                    artists.add(ar.getName());
                });
                song.setMusicArtists(Join.join(",", artists))
                        .setMusicImage(iteam.getAl().getPicUrl());
//                try {
//                    String s = FileUtil.downloadToBase64(iteam.getAl().getPicUrl());
//                    System.out.println("=================================");
//                    System.out.println(s);
//                    System.out.println("=================================");
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
                Rressong.add(song);

            });
            plugSearchResult.setSongs(Rressong);
            plugSearchResult.setPlugName(PlugName());
        }
        return plugSearchResult;
    }

    @Override
    public SqMusic musicDownload(@RequestBody DownloadParam downloadParam) throws PlugError {
        String lyircValue = null;
        //如果需要下载歌词
        if (downloadParam.isDownliadMusicLyric()) {
            LyricParam lyricParam = new LyricParam().setType_p(downloadParam.getType_p()).setId(downloadParam.getId());
            lyircValue = MusiclyricDownload(lyricParam).getLyric();
        } else {
            lyircValue = downloadParam.getMusicLyric();
        }
        JsososoDownloadParam jsososoDownloadParam = new JsososoDownloadParam().setType_p(downloadParam.getType_p()).setBr(downloadParam.getBr()).setId(downloadParam.getId());
        DownloadResult download = jsososoService.download(jsososoDownloadParam);
        if (download.getResult() == 100) {
            String url = download.getData().getUrl();
            String setVlaue = null;
            if (downloadParam.isTemp()) {
                //临时缓存
                setVlaue = setService.getOne(new QueryWrapper<SqSet>().eq("SetName", "SystemTempDownloadDir")).getSetVlaue();

            } else {
                setVlaue = setService.getOne(new QueryWrapper<SqSet>().eq("SetName", "SystemDownloadDir")).getSetVlaue();
            }
            String fileName = null;
            try {
                fileName = FileUtil.downloadToFile(url, setVlaue, downloadParam.getMusicName() + "-" + downloadParam.getMusicArtists());
            } catch (Exception e) {
                log.error("插件运行异常："+e.getMessage());
                throw new PlugError("插件运行io异常");
            }
            log.debug("下载地址：" + setVlaue);
            //是否下载图片
            if (downloadParam.isDownliadMusicImage()){
                String musicImage = downloadParam.getMusicImage();
                try {
                    downloadParam.setMusicImage(FileUtil.downloadToBase64(musicImage));
                } catch (IOException e) {
                    log.error("插件运行异常："+e.getMessage());
                    throw new PlugError("插件运行io异常");
                }
            }

            //保存到数据库中
            SqMusic sqMusic = null;
            try {
                sqMusic = new SqMusic()
                        .setMusicPath(fileName)
                        .setMusicName(downloadParam.getMusicName())
                        .setMusicAlbum(downloadParam.getMusicAlbum())
                        .setMusicArtists(downloadParam.getMusicArtists())
                        .setMusicSourImageUrl(downloadParam.getMusicImage())
                        .setMusicImage(FileUtil.downloadToFile(downloadParam.getMusicImage(), SQConstant.SYSTEM_IMAGE_DIR))
                        .setMusicDescribe(downloadParam.getMusicDescribe())
                        .setMusicLyric(lyircValue)
                        .setMusicCodeType(FileUtil.getFileSuffix(fileName).replaceAll(".", ""))
                        .setMusicTime(LocalDateTime.now())
                        .setMusicType(downloadParam.getMusicType());
            } catch (Exception e) {
                log.error("插件运行异常："+e.getMessage());
                throw new PlugError("插件运行io异常");
            }
            if (!downloadParam.isTemp()) {
                musicService.save(sqMusic);
            }

            return sqMusic;

        }
        return null;
    }

    @Override
    public PlugLyicResult MusiclyricDownload(@RequestBody LyricParam lyricParam) throws PlugError {
      return new PlugLyicResult().setLyric(jsososoService.Lyirc(lyricParam).getData().getLyric());
    }


}
